/**
 * 流式 AI 搜索接口
 * @param params 查询参数，参考 AiService.searchWithAiParams
 * @param options fetch 额外配置
 * @returns 可异步读取的 AI 回复字符串
 */
export async function searchWithAiStream(
  params: Record<string, string | number>,
  options?: RequestInit
): Promise<AsyncGenerator<string, void, unknown>> {
  // 获取 VITE_API_URL 环境变量
  const baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:9527';
  // 构建查询参数字符串
  const query = new URLSearchParams(params as Record<string, string>).toString();
  const url = `${baseUrl}/ai/search?${query}`;
    const token = localStorage.getItem('token');
  const headers = {
  'Authorization':  `${token}` ,
  'Content-Type': 'application/json',
      // 流式响应
    'Accept': 'text/event-stream',
};
  const response = await fetch(url, {
    method: 'GET',
    headers,
    ...(options || {}),
  });
 
  if (!response.body) {
    throw new Error('No stream body in response');
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder('utf-8');

  // 返回异步生成器，逐步读取流内容
  async function* streamGenerator() {
  let buffer = '';
  let done = false;
  while (!done) {
    const { value, done: readerDone } = await reader.read();
    if (value) {
      buffer += decoder.decode(value, { stream: true });
      let lines = buffer.split("\n");
      buffer = lines.pop() || "";
      for (const line of lines) {
        if (line.trim()) {
          yield line.replace(/^data:\s*/, ""); // 处理 SSE 的 "data: "
        }
      }
    }
    done = readerDone;
  }
  if (buffer.trim()) {
    yield buffer;
  }
}

  return streamGenerator();
}